{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import torch\n",
    "import torch.nn as nn"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "class temporal_channel_joint_attention(nn.Module):\n",
    "    def __init__(self, num_windows, num_channels, num_FBs, num_classes, num_heads=8, \n",
    "                 dim_feedforward=2048, num_encoder_layers=6):\n",
    "        super(temporal_channel_joint_attention, self).__init__()\n",
    "        self.temporal_attention = nn.TransformerEncoder(\n",
    "            nn.TransformerEncoderLayer(d_model=num_windows*num_FBs, nhead=num_heads, dim_feedforward=dim_feedforward, batch_first=True),\n",
    "            num_layers=num_encoder_layers\n",
    "        )\n",
    "        self.channel_attention = nn.TransformerEncoder(\n",
    "            nn.TransformerEncoderLayer(d_model=num_channels*num_FBs, nhead=num_heads, dim_feedforward=dim_feedforward, batch_first=True),\n",
    "            num_layers=num_encoder_layers\n",
    "        ) \n",
    "        self.fc = nn.Linear(2*num_windows*num_channels*num_FBs, num_classes)\n",
    "        self.dropout = nn.Dropout(0.5)\n",
    "        self.activation = nn.ReLU()\n",
    "\n",
    "    def forward(self, PSDs):\n",
    "        # PSDs: (batch_size, num_windows, num_channels, num_FBs)\n",
    "        # tokenization\n",
    "        temporal_tokens = PSDs.reshape(-1, num_windows, num_channels*num_FBs)\n",
    "        channel_tokens = PSDs.reshape(-1, num_channels, num_windows*num_FBs)\n",
    "        temporal_features = self.temporal_attention(temporal_tokens)\n",
    "        channel_features = self.channel_attention(channel_tokens)\n",
    "        # concat \n",
    "        temporal_features = temporal_features.reshape(-1, 1, num_windows*num_channels*num_FBs)\n",
    "        channel_features = channel_features.reshape(-1, 1, num_channels*num_windows*num_FBs)\n",
    "        joint_features = torch.cat((temporal_features, channel_features), dim=1)\n",
    "        # classification\n",
    "        joint_features = nn.Flatten()(joint_features)\n",
    "        joint_features = self.activation(joint_features)\n",
    "        joint_features = self.dropout(joint_features)\n",
    "        res = self.fc(joint_features)\n",
    "        return res"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "EEG",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.17"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
